package com.fram.service.api.v1.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fram.bean.api.integral.response.SignIntegralRuleBean;
import com.fram.bean.api.integral.response.SuccessSignInResponse;
import com.fram.bean.api.user.response.SignInResponse;
import com.fram.common.canstant.ErrCode;
import com.fram.common.enums.IntegRaluleEnum;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.BeanMapper;
import com.fram.common.util.date.DateUtils;
import com.fram.common.util.date.DateWeek;
import com.fram.common.util.json.JSONTools;
import com.fram.entity.Integral;
import com.fram.entity.IntegralRule;
import com.fram.entity.IntegralSignIn;
import com.fram.entity.IntegralTransactionFlow;
import com.fram.mapper.IntegralMapper;
import com.fram.mapper.IntegralRuleMapper;
import com.fram.mapper.IntegralSignInMapper;
import com.fram.mapper.IntegralTransactionFlowMapper;
import com.fram.service.api.v1.IntegralService;

@Service
public class IntegralServiceImpl implements IntegralService {
	@Autowired
	private IntegralSignInMapper integralSignInMapper;
	@Autowired
	private IntegralMapper integralMapper;
	@Autowired
	private IntegralTransactionFlowMapper integralTransactionFlowMapper;
	@Autowired
	private IntegralRuleMapper integralRuleMapper;
	SimpleDateFormat formatdate = new SimpleDateFormat("YYYY-MM-dd");
	/**累计签到  天数**/
	/** 新增 好比签到 点击 **/
	@Override
	public SuccessSignInResponse add(IntegralSignIn record) throws ProException {
		SuccessSignInResponse ses =new SuccessSignInResponse();
		if(!formatdate.format(record.getSignTime()).equals(formatdate.format(new Date()))) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
		List<Date> Listdate= integralSignInMapper.selectByDate(record.getUserId());
		int Days = DateUtils.continuityDay(record.getSignTime(), Listdate);
		/**积分  规则 拿出来**/
		IntegralRule news = integralRuleMapper.selectIntegral(IntegRaluleEnum.INTEGRAL.getMsg());
		System.out.println("");
		List<SignIntegralRuleBean> ruleBean = JSONTools.jsonStr2Array(news.getRuleGradeJson(),SignIntegralRuleBean.class);
		/**积分规则 跟 天数 判断 传多少积分**/
		Integer integral = 0;
		/**当天积分**/
		Integer same =0;
		for (SignIntegralRuleBean rule : ruleBean) {
			if(Days >= 1 && rule.getKey().equals("oneday")) {
				same=rule.getIntagral();
				record.setIntegral(same);
		}else if(Days == 3) {
			if(rule.getKey().equals("threeday")) {
				integral = rule.getIntagral();
				record.setIntegral(integral+same);
			}
		}else if(Days == 6) {
			if(rule.getKey().equals("sixdays")) {
				integral = rule.getIntagral();
				record.setIntegral(integral+same);
				}
			}
		}
		System.out.println(""+record.getIntegral());
		/**签到连续天数**/
		record.setSigns(Days);
		ses.setGet(record.getIntegral());
		// 签到（添加）
		if(integralSignInMapper.insertSelective(record)==0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// 总数放进 积分表
		Integral re = new Integral();
		re.setUserId(record.getUserId());
		re.setIntegral(record.getIntegral());
		if(integralMapper.insertSelective(re)==0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// 添加积分记录
		IntegralTransactionFlow flow = new IntegralTransactionFlow();
		flow.setUserId(record.getUserId());
		flow.setResId(record.getId());
		BigDecimal big= new BigDecimal(record.getIntegral().toString());
		flow.setIntegral(big);
		flow.setResType(7);
		flow.setFlowType(1);
		flow.setReason("签到积分");
		if(integralTransactionFlowMapper.insertSelective(flow)==0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
		Integer coun = integralMapper.selectByUserId(record.getUserId());
		ses.setTotal(coun);
		return ses;
	}

	/** 个人 签到积分查询日期 **/
	@Override
	public List<SignInResponse> listDate(Long userId, String date) throws ProException {
		// 拿到数据库的 记录日期
		List<SignInResponse> list = integralSignInMapper.listDate(userId);
		// 查询本月日历（参数是如 2020-05-01 就是展示5月）
		List<DateWeek> datelist = DateUtils.getMonthCalendar(date);
		// 定义一个map SignInResponse的
		Map<String, SignInResponse> signMap = new HashMap<String, SignInResponse>();
		// map放着 数据库记录日期 遍历出来
		for (SignInResponse response : list) {
			// 进行格式转换
			signMap.put(DateUtils.DF_SEPARATE_YMD.get().format(response.getSignTime()), response);
		}
		// 重新 new 新的 list SignInResponse这个类
		List<SignInResponse> newList = new ArrayList<SignInResponse>();
		// 遍历 5月的日历
		for (DateWeek dateWeek : datelist) {
			// 将遍历出来的日期 转换到 SignInResponse 这个类里
			SignInResponse response = BeanMapper.map(dateWeek, SignInResponse.class);
			// 判断signMap 数据库的签到的日期 和 5月日期 是否有相等的。
			if (signMap.containsKey(dateWeek.getDate())) {
				// 如果有Whether 1 显示库里的 SignTime数据
				response.setWhether(1);
				response.setSignTime(signMap.get(dateWeek.getDate()).getSignTime());
			}
			// 将最新 new 类 的放进去
			newList.add(response);
		}
		// 返回
		return newList;
	}
	/**积分规则展示**/
	@Override
	public IntegralRule listIntegral(String ruleKey) throws ProException {
		IntegralRule nee= integralRuleMapper.selectIntegral(ruleKey);
		if(nee == null ) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return nee;
	}
}
